package com.shbaiche.bifenba.ui.match;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.view.menu.MenuView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.shbaiche.bifenba.R;
import com.shbaiche.bifenba.model.base.TransMessage;
import com.shbaiche.bifenba.model.data.CompeteVo;
import com.shbaiche.bifenba.model.match.GoalStatVo;
import com.shbaiche.bifenba.model.match.MatchesLineupMessage;
import com.shbaiche.bifenba.model.match.MatchesListMessage;
import com.shbaiche.bifenba.model.match.MatchesOutsMessage;
import com.shbaiche.bifenba.model.match.MatchesVo;
import com.shbaiche.bifenba.model.match.SubstitutesVo;
import com.shbaiche.bifenba.model.video.ArticleVo;
import com.shbaiche.bifenba.net.JsonCallback;
import com.shbaiche.bifenba.net.NetApi;
import com.shbaiche.bifenba.ui.base.BaseFragment;
import com.shbaiche.bifenba.ui.video.VideoDetailActivity;
import com.shbaiche.bifenba.util.StringUtil;
import com.shbaiche.bifenba.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.droidlover.xdroidbase.imageloader.ILFactory;
import okhttp3.Call;

/**
 * 比赛详情-赛况
 */

@SuppressLint("ValidFragment")
public class MatchDetailLiveFragment extends BaseFragment {
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout refreshLayout;

    @BindView(R.id.layout_live_events)
    LinearLayout layoutEvents;

    @BindView(R.id.layout_live_count)
    LinearLayout layoutCount;

    @BindView(R.id.layout_live_news)
    LinearLayout layoutNews;

    @BindView(R.id.tv_name_home)
    TextView tvNameHome;

    @BindView(R.id.tv_name_visit)
    TextView tvNameVisit;

    @BindView(R.id.iv_logo_home)
    ImageView ivLogoHome;

    @BindView(R.id.iv_logo_visit)
    ImageView ivLogoVisit;



    MatchesVo mMatchVo;

    @SuppressLint("ValidFragment")
    public MatchDetailLiveFragment(){

    }

    public static MatchDetailLiveFragment newInstance() {
        return new MatchDetailLiveFragment();
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        if(savedInstanceState!=null && savedInstanceState.containsKey("data")){
            mMatchVo = (MatchesVo)savedInstanceState.getSerializable("data");
        }else{
            mMatchVo = (MatchesVo)getArguments().getSerializable("data");
        }

       loadData();

        tvNameHome.setText(mMatchVo.getHomeName());
        tvNameVisit.setText(mMatchVo.getVisitName());

        ILFactory.getLoader().loadNet(ivLogoHome, mMatchVo.getHomeLogo(), null);
        ILFactory.getLoader().loadNet(ivLogoVisit, mMatchVo.getVisitLogo(), null);





        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadData();
            }
        });

    }

    private void setViews(MatchesOutsMessage message){
        if(message!=null){

            setEvents(message.getSubList());
            setNews(message.getRelatedList());
            setCounts(message.getStatList());
        }
    }

    private void setEvents(List<SubstitutesVo> list){
        layoutEvents.removeAllViewsInLayout();
        if(list!=null){
            SubstitutesVo item;
            for (int i = 0; i< list.size();i++){
                item = list.get(i);
                View viewItem = View.inflate(getContext(),R.layout.layout_match_detail_live_event_item,null);
                TextView tvMinute = (TextView)viewItem.findViewById(R.id.tv_minute);
                LinearLayout layoutLeft = (LinearLayout) viewItem.findViewById(R.id.layout_left);
                LinearLayout layoutRight = (LinearLayout) viewItem.findViewById(R.id.layout_right);

                tvMinute.setText(""+item.getMinute());

                if(item.getType() == 1){
                    layoutRight.setVisibility(View.INVISIBLE);
                    setEventContent(item.getType(),layoutLeft,item);

                }else if(item.getType() == 2){
                    layoutLeft.setVisibility(View.INVISIBLE);
                    setEventContent(item.getType(),layoutRight,item);
                }

                layoutEvents.addView(viewItem);
            }
        }


    }

    private void setEventContent(int type,LinearLayout layout,SubstitutesVo vo){
        if(layout!=null && vo!=null){
            LinearLayout layout2;
            TextView tvName,tvName2;
            ImageView ivIcon;
            if(type == 1){
                layout2 = (LinearLayout)layout.findViewById(R.id.layout_left_2);
                tvName= (TextView)layout.findViewById(R.id.tv_left_name);
                tvName2= (TextView)layout.findViewById(R.id.tv_left_name_2);
                ivIcon = (ImageView)layout.findViewById(R.id.iv_left_icon);
            }else{
                layout2 = (LinearLayout)layout.findViewById(R.id.layout_right_2);
                tvName= (TextView)layout.findViewById(R.id.tv_right_name);
                tvName2= (TextView)layout.findViewById(R.id.tv_right_name_2);
                ivIcon = (ImageView)layout.findViewById(R.id.iv_right_icon);
            }


            if(vo.getEvent() == 9 ){
                layout2.setVisibility(View.VISIBLE);
                tvName.setText(vo.getUpname());
                tvName2.setText(vo.getDownname());
            }else{
                tvName.setText(vo.getpName());
                layout2.setVisibility(View.GONE);
            }
            // 事件名称0: 进球, 1: 点球, 2: 乌龙球, 3: 黄牌, 4: 红牌, 5: 两黄变一红 8：点球射失 9:球员替换
            switch (vo.getEvent()){
                case 0:
                    ivIcon.setImageResource(R.drawable.icon_event_goals);
                    break;
                case 1:
                    ivIcon.setImageResource(R.drawable.icon_event_penalties);
                    break;
                case 2:
                    ivIcon.setImageResource(R.drawable.icon_event_own_goals);
                    break;
                case 3:
                    ivIcon.setImageResource(R.drawable.icon_event_yellow_brand);
                    break;
                case 4:
                    ivIcon.setImageResource(R.drawable.icon_event_red_brand);
                    break;
                case 5:
                    ivIcon.setImageResource(R.drawable.icon_event_double_yellow_to_red);
                    break;
                case 9:

                    break;
                default:
                    ivIcon.setVisibility(View.GONE);
                    break;
            }

        }
    }


    private void setCounts(List<GoalStatVo> list){
        layoutCount.removeAllViewsInLayout();
        if(list!=null){
            GoalStatVo item;
            for (int i = 0; i< list.size();i++){
                item = list.get(i);
                View viewItem = View.inflate(getContext(),R.layout.layout_match_detail_live_count_item,null);
                TextView tvName = (TextView) viewItem.findViewById(R.id.tv_name);
                TextView tvValueHome = (TextView) viewItem.findViewById(R.id.tv_value_home);
                TextView tvValueAway = (TextView) viewItem.findViewById(R.id.tv_value_away);
                LinearLayout layoutHome = (LinearLayout)viewItem.findViewById(R.id.layout_value_home);
                LinearLayout layoutAway = (LinearLayout)viewItem.findViewById(R.id.layout_value_away);
                View viewHome = viewItem.findViewById(R.id.view_value_home);
                View viewAway = viewItem.findViewById(R.id.view_value_away);

                LinearLayout.LayoutParams lpHome = null,lpAway = null;

                tvName.setText(item.getName());
                float valHome = 0 , valAway = 0;

                tvValueHome.setText(item.getHome());
                tvValueAway.setText(item.getAway());

                if(!TextUtils.isEmpty(item.getHome()) && !TextUtils.isEmpty(item.getAway())){

                    try{
                        if(item.getHome().contains("%") && item.getAway().contains("%")){
                            valHome = Integer.valueOf(item.getHome().replaceAll("%",""));
                            valAway = Integer.valueOf(item.getAway().replaceAll("%",""));

                            lpHome = new LinearLayout.LayoutParams(0,-1,valHome);
                            lpAway = new LinearLayout.LayoutParams(0,-1,valAway);

                        }else{
                            valHome = Integer.valueOf(item.getHome());
                            valAway = Integer.valueOf(item.getAway());

                            layoutHome.setWeightSum(valHome+valAway);
                            layoutAway.setWeightSum(valHome+valAway);

                        }

                        lpHome = new LinearLayout.LayoutParams(0,-1,valHome);
                        lpAway = new LinearLayout.LayoutParams(0,-1,valAway);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }else if("*".equals(item.getHome()) || "*".equals(item.getAway())){
                    layoutHome.setWeightSum(1);
                    layoutAway.setWeightSum(1);


                    if("*".equals(item.getHome())){

                        lpHome = new LinearLayout.LayoutParams(0,-1,1);
                        lpAway = new LinearLayout.LayoutParams(0,-1,0);
                    }else{
                        lpHome = new LinearLayout.LayoutParams(0,-1,0);
                        lpAway = new LinearLayout.LayoutParams(0,-1,1);
                    }

                }
                if(lpHome!=null && lpAway!=null){
                    viewHome.setLayoutParams(lpHome);
                    viewAway.setLayoutParams(lpAway);
                }

                layoutCount.addView(viewItem);
            }
        }

    }

    private void setNews(List<ArticleVo> list){
        layoutNews.removeAllViewsInLayout();
        if(list!=null){
            ArticleVo item;
            for (int i = 0; i< list.size();i++){
                item = list.get(i);
                View viewItem = View.inflate(getContext(),R.layout.layout_match_detail_live_news_item,null);
                TextView tvTitle = (TextView) viewItem.findViewById(R.id.tv_title);
                TextView tvCount = (TextView) viewItem.findViewById(R.id.tv_count);
                ImageView ivLogo = (ImageView) viewItem.findViewById(R.id.iv_logo);

                viewItem.setTag(item.getId());
                tvTitle.setText(item.getTitle());
                tvCount.setText(item.getBrowseNum()+"浏览");
                ILFactory.getLoader().loadNet(ivLogo, item.getThumbnail(), null);
                viewItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try{
                            Bundle b = new Bundle();
                            b.putLong("id", Long.valueOf(v.getTag().toString()));
                            VideoDetailActivity.launch(getActivity(), b);
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                    }
                });
                layoutNews.addView(viewItem);
            }
        }


    }



    public void loadData() {
        MatchesOutsMessage message = new MatchesOutsMessage();
        message.setCompeteId(mMatchVo.getCompeteId());
        message.setGameType(mMatchVo.getGameType());
        message.setGameId(mMatchVo.getGameId());

        NetApi.matchesOuts(message, new JsonCallback<TransMessage>() {
            @Override
            public void onFail(Call call, Exception e, int id) {
                refreshLayout.setRefreshing(false);
                ToastUtil.show("onFail" + e.getMessage());
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                refreshLayout.setRefreshing(false);
                ToastUtil.show("onFail" + e.getMessage());

            }

            @Override
            public void onResponse(TransMessage response, int id) {
                refreshLayout.setRefreshing(false);
                MatchesOutsMessage result =new Gson().fromJson(response.getMessage(),MatchesOutsMessage.class);
                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, result.getCode())) {
                    if(result!=null){
                        Log.e("t","onResponse");
                        setViews(result);
                    }
                }else{
                    Log.e("t","onResponse getCode "+response.getCode());
                    ToastUtil.show(result.getMessage());
                }
            }
        });





    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_match_detail_live;
    }
}
